package xyz.lilei123.sessiondemo.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import xyz.lilei123.sessiondemo.dto.UserDto;
import xyz.lilei123.sessiondemo.service.IUserService;

import javax.servlet.http.HttpSession;

/**
 * @author jack
 * @version 1.0
 * @date 05/09/2021 17:15
 **/
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private IUserService userService;

    @PostMapping(value="/login")
    public String login(UserDto userDto, HttpSession session) {
        UserDto userDto1 = userService.getUserByName(userDto.getUsername());
        if (userDto1 == null || !userDto1.checkPassword(userDto)){
            // 非法用户返回登录页面
            System.out.println("非法，跳转");
            return "redirect:/login/toLogin";
        }else {
            System.out.println("合法用户");
            session.setAttribute("username",userDto.getUsername());
            return "redirect:/user/get";
        }
    }

    @PostMapping(value="/loginOut")
    public String loginOut(HttpSession session) {
        session.removeAttribute("user");
        session.removeAttribute("username");
        // 非法用户返回登录页面
        System.out.println("注销，跳转");
        return "redirect:/login/toLogin";
    }

    @GetMapping("/toLogin")
    public String toLogin() {
        System.out.println("================++++++++++++++跳转登录页面");
        return "login";
    }
}
